package com.easy.service.impl;

import com.easy.bean.User;
import com.easy.mapper.UserMapper;
import com.easy.service.LoginService;
import com.easy.util.PasswordUtil;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User logininfo(String token) {
        //获取用户id(token中存的)
        Object id = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        if (id == null) {
            throw new RuntimeException("登录异常");
        }
        User user = userMapper.one(Integer.parseInt(id.toString()));
        return user;
    }


    @Override
    public String login(User user) {
        //登录逻辑
        //1.通过用户手机号查询数据库
        User result = userMapper.getByPhone(user.getPhone());
        if (result == null) {
            throw new RuntimeException("用户不存在");
        }
        //2.验证密码
        String password = user.getPassword();//123123
        String encryptionPassword = result.getPassword();//密文
        if (!PasswordUtil.checkPassword(password, encryptionPassword)) {
            throw new RuntimeException("密码错误");
        }
        //3.返回结果token
        String token = TokenUtil.getToken(result.getId(), "user");
        return token;
    }


}
